﻿using AutoMapper.Internal.Mappers;
using Business.BookManagement.Dto;
using Business.BookManagement;
using Business.Permissions;
using Microsoft.AspNetCore.Authorization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Domain.Repositories;
using XCZ;
using Business.Models;
using Business.ProduceManagement.Dto;
using Microsoft.EntityFrameworkCore;

namespace Business.ProduceManagement
{

    public class ProduceAppService : BusinessWorkFlowAppService, IProduceAppService
    {
        private const string FormName = "Produce";
        private IRepository<Produce, Guid> _repository;

        public ProduceAppService(IRepository<Produce, Guid> repository)
        {
            _repository = repository;
        }

        #region 增删改查基础方法

        public async Task<ProduceDto> Get(Guid id)
        {
            var data = await _repository.GetAsync(id);
            var dto = ObjectMapper.Map<Produce, ProduceDto>(data);
            return dto;
        }

        public async Task<PagedResultDto<ProduceDto>> GetAll(GetProduceInputDto input)
        {
            var query = (await _repository.GetQueryableAsync()).WhereIf(!string.IsNullOrWhiteSpace(input.Filter), a => a.ProName.Contains(input.Filter));

            var totalCount = await query.CountAsync();
            var items = await query.OrderBy(input.Sorting ?? "Id")
                        .ToListAsync();

            var dtos = ObjectMapper.Map<List<Produce>, List<ProduceDto>>(items);
            return new PagedResultDto<ProduceDto>(totalCount, dtos);
        }

        public async Task<ProduceDto> CreateOrUpdate(CreateOrUpdateProduceDto input)
        {
            Produce result = null;
            if (!input.Id.HasValue)
            {
                input.Id = GuidGenerator.Create();
                var infos = ObjectMapper.Map<CreateOrUpdateProduceDto, Produce>(input);
                result = await _repository.InsertAsync(infos);

                //创建工作流
                //await WorkFlow.CreateWorkFlow(FormName, result);
            }
            else
            {
                var data = await _repository.GetAsync(input.Id.Value);
                result = await _repository.UpdateAsync(ObjectMapper.Map(input, data));
                //检查流程状态
                // await WorkFlow.CheckFormStatus(input.Id.Value, result);
            }
            return ObjectMapper.Map<Produce, ProduceDto>(result);
        }

        public async Task Delete(List<Guid> ids)
        {
            foreach (var item in ids)
            {
                await _repository.DeleteAsync(item);
            }

        }
        #endregion

    }
}
